#include "CF.h"
#include "CF_SceneWindow.h"
#include "CF_NewSceneDialog.h"
#include "CF_WorkspaceManager.h"

#include <QTreeWidgetItem>
#include <QContextMenuEvent>

CF_SceneWindow::CF_SceneWindow(QWidget *parent)
	: CL_Widget(parent)
{
	ui.setupUi(this);

	// toolbar
    m_toolBar = new QToolBar(this);
    m_toolBar->setObjectName(tr("sceneToolBar"));
	ui.gridLayout->addWidget(m_toolBar,0,0,1,1);

	QPixmap iconNewScene(tr(":/Icon/Plus"));
	QAction* actionNewScene = m_toolBar->addAction(QIcon(iconNewScene), tr("New Scene"));
	m_toolBar->setIconSize(iconNewScene.size());

	QObject::connect(actionNewScene, SIGNAL(triggered()), this, SLOT(newScene()));

	// context menu
	m_contextMenu = new QMenu(this);
	QAction* newSceneAction			= m_contextMenu->addAction(tr("New scene ..."));
	QAction* switchToSceneAction	= m_contextMenu->addAction(tr("Switch to scene"));

	QObject::connect(newSceneAction, SIGNAL(triggered()), this, SLOT(newScene()));
	QObject::connect(switchToSceneAction, SIGNAL(triggered()), this, SLOT(switchToScene()));

	// scene tree
	QStringList headerList;
	headerList << tr("Name");
	ui.sceneTree->setHeaderLabels(headerList);
	ui.sceneTree->setRootIsDecorated(false);
}

CF_SceneWindow::~CF_SceneWindow()
{
	delete m_toolBar;
}

void CF_SceneWindow::updated(CL_UpdatedContext* context)
{
	switch(context->reason())
	{
	case CF_UpdatedReason::NEW_WORKSPACE:
		{
			//CF_NewWorkspaceContext* param = static_cast<CF_NewWorkspaceContext*>(context);
		}
		break;
	case CF_UpdatedReason::OPEN_WORKSPACE:
		{
			//CF_OpenWorkspaceContext* param = static_cast<CF_OpenWorkspaceContext*>(context);
			reloadWorkspace();
		}
		break;
	case CF_UpdatedReason::NEW_SCENE:
		break;
	}
}

void CF_SceneWindow::newScene()
{
	CF_NewSceneDialog dlg(this);
	if(!dlg.exec())
		return;

	QTreeWidgetItem* newItem = new QTreeWidgetItem(ui.sceneTree);
	newItem->setText(0, dlg.getName());

	CE_Scene* newScene = workspaceManager->createScene(dlg.getName());
	workspaceManager->save();
	newScene->setCurrentScene();

	notifyUpdated(new CF_NewSceneContext(dlg.getName()));
}

void CF_SceneWindow::switchToScene()
{
	QTreeWidgetItem* currentItem = ui.sceneTree->currentItem();
	if(currentItem==NULL)
		return;
	QString currentSceneName = currentItem->text(0);
	CE_Scene* node = workspaceManager->getSceneByName(currentSceneName);
	CF_ASSERT(node, "Scene does not exist");
	node->setCurrentScene();
}

void CF_SceneWindow::reloadWorkspace()
{
	for(int iScene=0; iScene<workspaceManager->getSceneCount(); iScene++)
	{
		QTreeWidgetItem* newItem = new QTreeWidgetItem(ui.sceneTree);
		CE_Scene* node = workspaceManager->getScene(iScene);
		newItem->setText(0, node->sceneName());
	}
}

void CF_SceneWindow::contextMenuEvent(QContextMenuEvent* e)
{
	m_contextMenu->popup(e->globalPos());
}
